<!-- 上门整治 -->
<template>
  <div class="app-container">
    <!-- 原有的内容 -->
    <el-form
      v-show="showSearch"
      ref="queryRef"
      :model="queryParams"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="区县" prop="district">
        <el-select
          v-model="queryParams.district"
          clearable
          placeholder="请选择区县"
          @change="handleCountyChange"
          style="width: 120px"
        >
          <el-option
            v-for="c in countyOptions"
            :key="c"
            :label="c"
            :value="c"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="网格名称" prop="gridName">
        <el-select
          v-model="queryParams.by1"
          clearable
          placeholder="请选择网格名称"
          style="width: 220px"
        >
          <el-option
            v-for="grid in gridOptions"
            :key="grid"
            :label="grid"
            :value="grid"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="realName">
        <el-input
          v-model="queryParams.realName"
          placeholder="请输入代维姓名"
          clearable
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>
      <!-- <el-form-item label="代维ID" prop="maintainerId" label-width="82px">
        <el-input
          v-model="queryParams.maintainerId"
          placeholder="请输入代维人员ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="考核时间" prop="ofTime">
        <el-date-picker
          style="width: 140px"
          v-model="queryParams.ofTime"
          clearable
          type="month"
          value-format="YYYY-MM"
          format="YYYY-MM"
          placeholder="请选择考核时间"
          :default-value="null"
          :disabled-date="disabledDate"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 一键导入 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="18">
        <div style="display: flex; align-items: center">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:order:export']"
          >导出</el-button>

          <el-button
            v-hasPermi="['system:income:remove']"
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            >删除</el-button
          >
        </div>
      </el-col>
    </el-row>

    <!-- <el-row>
      <right-toolbar :show-search="showSearch" @queryTable="getList" />
    </el-row> -->

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="incomeList"
      border
      :resizable="true"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="序号" align="center" width="60">
        <template #default="scope">
          {{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}
        </template>
      </el-table-column>
      <el-table-column label="区县" align="center" prop="district" />
      <el-table-column label="网格名称" align="center" prop="by1" width="120" />
      <el-table-column label="姓名" align="center" prop="realName" />
      <el-table-column label="代维ID" align="center" prop="maintainerId" />
      <el-table-column
        label="单用户中断奖励"
        align="center"
        prop="singleUserReward"
        width="120"
      />
      <el-table-column
        label="单用户中断扣罚"
        align="center"
        prop="singleUserPenalty"
        width="120"
      />
      <el-table-column
        label="0NU弱光奖励"
        align="center"
        prop="weakLightReward"
        width="110"
      />
      <el-table-column
        label="0NU弱光扣罚"
        align="center"
        prop="weakLightPenalty"
        width="110"
      />
      <el-table-column
        label="网络割接奖励"
        align="center"
        prop="networkCutoverReward"
        width="110"
      />
      <el-table-column label="薪酬小计" align="center" prop="rectifySubtotal" />
      <el-table-column label="考核时间" align="center" prop="ofTime" />
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page="queryParams.pageNum"
      :limit="queryParams.pageSize"
      @pagination="handlePagination"
    />
  </div>
</template>

<script>
import { rectify, delIncome, uploadFile, importData } from "@/api/dwxc/salary";
import { parseTime } from "@/utils/ruoyi";
import { listIncome, getGridName } from "@/api/dwxc/income";
import Pagination from "@/components/Pagination";
import SparkMD5 from "spark-md5";
import { download } from "@/utils/request";
import { listCounty } from "@/api/dwxc/information";

export default {
  name: "Income",
  components: {
    Pagination,
  },
  data() {
    return {
      showExportButton: false,
      // 原有数据
      salaryList: [],
      total: 0,
      loading: true,
      importing: false,
      showSearch: true,
      single: false,
      multiple: false,
      isFirstLoad: true, // 标记是否为首次加载
      urbanRuralOptions: [
        { label: "城区", value: "城区" },
        { label: "乡镇", value: "乡镇" },
        { label: "待确认", value: "待确认" },
      ],
      // countyOptions: [
      //   "浔阳区",
      //   "濂溪区",
      //   "柴桑区",
      //   "瑞昌市",
      //   "共青城",
      //   "庐山市",
      //   "武宁县",
      //   "修水县",
      //   "永修县",
      //   "德安县",
      //   "都昌县",
      //   "湖口县",
      //   "彭泽县",
      // ],
      // // 区县名称映射表（显示名称 -> 接口参数名称）
      // districtNameMap: {
      //   浔阳区: "浔阳",
      //   濂溪区: "濂溪",
      //   柴桑区: "柴桑",
      //   瑞昌市: "瑞昌",
      //   共青城: "共青",
      //   庐山市: "庐山",
      //   武宁县: "武宁",
      //   修水县: "修水",
      //   永修县: "永修",
      //   德安县: "德安",
      //   都昌县: "都昌",
      //   湖口县: "湖口",
      //   彭泽县: "彭泽",
      // },

      // 保留并初始化countyOptions为空数组
      countyOptions: [],

      queryParams: {
        pageNum: 1,
        pageSize: 10,
        district: null,
        realName: null,
        maintainerId: null,
        urbanRuralClass: null,
        salaryRange: null,
        fullSalaryRange: null,
        ofTime: null,
      },
      selectedRows: [],
      // 导入文件列表，避免重复导入
      importedFiles: [],
      selectedFileHash: null, // 记录当前选择文件的哈希值
      uploadedFileHashes: [], // 记录已上传过的文件哈希值
      uploadedFilePath: null, // ✅ 使用 res.fileName
    };
  },

  created() {
    this.getList();
    this.getCountyList(); // 添加区县列表获取
  },

  methods: {
    parseTime,
    handleAdd() {},
    handleUpdate() {},
    // 添加获取区县列表的方法
    getCountyList() {
      listCounty().then(res => {
        // 根据实际返回的数据结构进行处理
        // 直接返回了数组，而不是 {code: 200, data: [...]} 的结构
        if (Array.isArray(res)) {
          this.countyOptions = res;
        } else if (res && res.code === 200 && Array.isArray(res.data)) {
          // 如果是标准的 {code: 200, data: [...]} 格式
          this.countyOptions = res.data;
        } else {
          console.error("无效的区县数据格式:", res);
          this.$message.error("获取区县列表失败: 数据格式错误");
        }
      }).catch(error => {
        console.error("获取区县列表失败:", error);
        this.$message.error("获取区县列表失败");
      });
    },
    disabledDate(time) {
      // Disable current month and future months
      const currentDate = new Date();
      const currentYear = currentDate.getFullYear();
      const currentMonth = currentDate.getMonth(); // 0-11

      const selectedDate = new Date(time);
      const selectedYear = selectedDate.getFullYear();
      const selectedMonth = selectedDate.getMonth(); // 0-11

      // Disable if selected date is current or future month
      return (
        selectedYear > currentYear ||
        (selectedYear === currentYear && selectedMonth >= currentMonth)
      );
    },
    handleFileChangeAndImport(fileEvent) {
      const file = fileEvent.target.files[0];
      if (!file) return;

      this.selectedFile = file;
      this.$message.info("已选择文件: " + file.name);

      // 生成文件哈希值
      const reader = new FileReader();
      reader.onload = (e) => {
        const spark = new SparkMD5.ArrayBuffer();
        spark.append(e.target.result);
        const fileHash = spark.end();
        this.selectedFileHash = fileHash;

        // 检查是否已上传过该文件
        if (this.uploadedFileHashes.includes(fileHash)) {
          this.$message.warning("该文件内容已上传过，请勿重复上传");
          return;
        }

        // 开始上传
        this.uploadFileAndImport();
      };
      reader.readAsArrayBuffer(file);
    },

    // 上传文件并导入数据
    uploadFileAndImport() {
      if (!this.selectedFile) {
        this.$message.warning("请先选择一个文件");
        return;
      }
      if (!this.selectedFileHash) {
        this.$message.warning("文件哈希未生成，请稍等");
        return;
      }
      if (this.uploadedFileHashes.includes(this.selectedFileHash)) {
        this.$message.warning("该文件内容已上传过，请勿重复上传");
        return;
      }

      const formData = new FormData();
      formData.append("file", this.selectedFile);
      this.loading = true;

      // 1. 上传文件
      uploadFile(formData)
        .then((res) => {
          if (res && res.code === 200) {
            this.$message.success("文件上传成功");
            this.uploadedFilePath = res.fileName;
            this.uploadedFileHashes.push(this.selectedFileHash);

            // 2. 导入数据
            return this.importDataAndRefresh();
          } else {
            this.$message.error(res.msg || "服务器未返回文件路径");
            this.loading = false;
          }
        })
        .catch((err) => {
          this.$message.error("文件上传失败");
          console.error("上传失败:", err);
          this.loading = false;
        });
    },

    // 导入数据并刷新表格
    importDataAndRefresh() {
      if (!this.uploadedFilePath) {
        this.$message.warning("请先上传文件");
        this.loading = false;
        return;
      }
      if (this.importedFiles.includes(this.uploadedFilePath)) {
        this.$message.warning("该文件已导入过");
        this.loading = false;
        return;
      }

      this.importing = true;

      const backendPath =
        "C:\\ruoyi\\uploadPath\\" +
        this.uploadedFilePath.replace("/profile/", "");

      // 3. 调用导入接口
      importData({ filePath: backendPath })
        .then((res) => {
          if (res && res.code === 0) {
            this.$message.success("导入成功");
            this.getList(); // 4. 刷新表格

            // 清空文件状态
            this.uploadedFilePath = null;
            this.selectedFile = null;
            this.$refs.uploadRef?.clearFiles();

            this.importedFiles.push(this.uploadedFilePath);
          } else {
            this.$message.error(res.msg || "导入失败");
          }
        })
        .catch((err) => {
          this.$message.error("导入失败");
          console.error("导入失败:", err);
        })
        .finally(() => {
          this.importing = false;
          this.loading = false;
        });
    },
    handleDelete() {
      if (!this.selectedRows || this.selectedRows.length === 0) {
        this.$message.warning("请至少选择一条数据");
        return;
      }

      const ids = this.selectedRows.map((row) => row.id); // 假设数据中有 id 字段
      console.log("准备删除的 ids:", ids);

      this.$confirm("是否确认删除选中的数据项?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log("调用 delIncome");
          delIncome(ids)
            .then((res) => {
              console.log("删除结果:", res);
              if (res.code === 200) {
                this.$message.success("删除成功");
                this.getList(); // 刷新列表
              } else {
                this.$message.error(res.msg || "删除失败");
              }
            })
            .catch((err) => {
              this.$message.error("请求失败");
              console.error("删除失败:", err);
            });
        })
        .catch(() => {
          // 取消操作
        });
    },
    /**
     * 导出按钮操作
     */
    handleExport() {
      download('/salary/rectifyExport', {
        ...this.queryParams
      }, `上门整治数据_${new Date().getFullYear()}${(new Date().getMonth() + 1).toString().padStart(2, '0')}${new Date().getDate().toString().padStart(2, '0')}.xlsx`)
    },

    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        district: null,
        channelId: null,
        channelName: null,
      };
      this.getList();
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handlePagination(page) {
      this.queryParams.pageNum = page.page;
      this.queryParams.pageSize = page.limit;
      this.getList();
    },
    getList() {
      this.loading = true;
      rectify(this.queryParams)
        .then((res) => {
          console.log("原始 res：", res);
          // 提取 rows 数组
          const list = res.rows || [];
          this.incomeList = list;
          // 提取 total
          this.total = res.total || list.length;
          this.loading = false;
        })
        .catch((error) => {
          console.error("获取收入数据失败:", error);
          this.loading = false;
          this.$message.error("获取数据失败");
          this.salaryList = [];
          this.total = 0;
        });
    },

    // 修改handleCountyChange方法（使用简称）
    handleCountyChange(val) {
      console.log("选中的区县：", val);
      this.queryParams.by1 = ""; // 清空网格选择
      if (val) {
        // 直接使用接口返回的简称（如"湖口"）
        getGridName(val)
          .then((res) => {
            // 处理网格数据...
            if (Array.isArray(res)) {
              this.gridOptions = res;
            } else if (res.data && Array.isArray(res.data)) {
              this.gridOptions = res.data;
            } else {
              this.gridOptions = [];
              console.warn("网格数据格式异常:", res);
            }
          })
          .catch((error) => {
            console.error("获取网格失败:", error);
            this.$message.error("获取网格失败");
          });
      } else {
        this.gridOptions = [];
      }
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
      console.log("已选行", this.selectedRows);
    },
  },
};
</script>

<style scoped>
.test-section {
  border: 1px solid #e1f5fe;
}
</style>
